import 'dart:async';
import 'dart:math';
import 'package:flutter/material.dart';
import 'package:flutter_app_minimizer_plus/flutter_app_minimizer_plus.dart';
import 'package:flutter_overlay_window/flutter_overlay_window.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:smart_translator/app/event/DataCallBack.dart';
import 'package:smart_translator/app/services/AudioService.dart';
import 'package:flutter_svg/svg.dart';

import 'package:get/get.dart';
import 'package:smart_translator/app/style/widget_style.dart';
import 'package:smart_translator/app/widgets/CommonWidgets.dart';
import '../../../const/AppConst.dart';
import '../../../db/DbDAOHelper.dart';
import '../../../nets/NetWorkManager.dart';
import '../../../routes/app_pages.dart';
import '../../../style/app_colors.dart';
import '../../../utils/CommonUtil.dart';
import '../../../utils/tips.dart';
import '../../../widgets/AppHeader.dart';
import '../../../widgets/AudioWaveform.dart';
import '../controllers/real_translation_controller.dart';

class RealTranslationView extends GetView<RealTranslationController> {
  RealTranslationView({super.key});

  @override
  Widget build(BuildContext context) {
    return RealTranslationViewStateful(controller);
  }
}


class RealTranslationViewStateful extends StatefulWidget {
  
  
  RealTranslationViewStateful(RealTranslationController controller, {super.key});


  @override
  State<StatefulWidget> createState() {
    return RealTranslateViewState();
  }


}

class RealTranslateViewState extends State<RealTranslationViewStateful>  with SingleTickerProviderStateMixin {

  AnimationController?  animationController;
  late Animation<double> rotation;

  bool hasRotated = false;


  final ScrollController fromController = ScrollController();
  final ScrollController toController = ScrollController();



  AudioService audioService = Get.find<AudioService>();

  RealTranslationController? realTranslationController;

  // 防抖计时器
  Timer? _debounceTimer;
  // 是否处于冷却状态
  bool _isCoolingDown = false;

  RxList<double> amplitudes =  RxList.generate(50, (index) => Random().nextDouble()*0.1);
  Timer? _audioWavetimer;

  @override
  void initState() {
    super.initState();

    realTranslationController = Get.put(RealTranslationController());

    animationController = AnimationController(
        vsync: this, // 直接传递 State 自身作为 TickerProvider
        duration: Duration(milliseconds: 200),
    );

    rotation = Tween<double>(begin: 0, end: 0.5)
        .animate(CurvedAnimation(
      parent: animationController!,
      curve: Curves.easeInOut,
    ));

    // _openRecorder();
    // realTimeTranscription();

    Future.delayed(Duration(milliseconds: 500),() {
      initWsAndRecorder();

    });

  }

  void initWsAndRecorder() {
    audioService.initAllState();
    audioService.connectedWsAndRecorder('wss://${NetWorkManager.WS_IP+NetWorkManager.SPEECH_RECOGNITION}?transStrategy=1&enableInterlingual=1',  DataCallBack(
        confirmCallBack: (v) {

        },
        businessCallBack: (m) {
          fromScrollToBottom();
          toScrollToBottom();
        }
    ));
  }


  void fromScrollToBottom() {
    if (fromController.hasClients) {
      Future.delayed(Duration(milliseconds: 500),() {
        fromController.animateTo(
          fromController.position.maxScrollExtent,
          duration: const Duration(milliseconds: 300),
          curve: Curves.easeOut,
        );
      });
    }
  }

  void toScrollToBottom() {
    if (toController.hasClients) {
      toController.animateTo(
        toController.position.maxScrollExtent,
        duration: const Duration(milliseconds: 300),
        curve: Curves.easeOut,
      );
    }
  }

  @override
  Widget build(BuildContext context) {
    return SafeArea(child: Scaffold(
        body: SingleChildScrollView(
          child: Stack(
            children: [
              Container(
                child: SvgPicture.asset(
                  "assets/images/header_part_bg.svg",
                  width: Get.width,
                ),
              ),
              AppHeader.obtainHeaderForRealTranslation(DataCallBack(
                confirmCallBack: (v) {
                  showAudioLogsPoupWindow(context);
                },
                businessCallBack: (v) {
                    quite();
                }
              )),
              Obx(()=> Column(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Container(
                    width: Get.width,
                    margin: EdgeInsets.only(top: 70.h),
                    padding: EdgeInsets.all(20.w),
                    child: Column(
                      children: [
                        RotationTransition(
                          turns: rotation,
                          child:  Container(
                            width: Get.width,
                            height: 278.h,
                            decoration: BoxDecoration(
                              color:  Colors.white,
                              borderRadius: BorderRadius.only(topLeft: Radius.circular(8),topRight: Radius.circular(8)), // Optional: add border radius
                            ),
                            child: Stack(
                              children: [
                                audioService.finalFromLanguage.value == '' ? Container(
                                  child: Center(
                                    child: Column(
                                      children: [
                                        SizedBox(height: 80.h,),
                                        Image.asset('assets/images/empty_list_realtime.png',width: 169.w,height: 91.h),
                                        SizedBox(height: 16.h,),
                                        Text('点击下方开始键开始同声翻译',style: AppStyleThemeData.HINT_TEXT_STYLE_small,)

                                      ],
                                    ),
                                  ),
                                ): Container(
                                  padding: EdgeInsets.only(top: 45.h,left: 20.w,right: 20.w),
                                  child: SingleChildScrollView(
                                    controller: toController,
                                    child: Text(audioService.finalToLanguage.value,style: TextStyle(
                                        color: AppColors.big_title_color,
                                        fontSize: realTranslationController!.fontSize.value.sp
                                    )),
                                  ),
                                ),
                                Positioned(
                                  child: Text('${audioService.toLanFlagDisplay.value}',style: AppStyleThemeData.HINT_TEXT_STYLE_small),
                                  left: 15.w,
                                  top: 15.h,
                                )
                              ],
                            ),
                          ),
                        ),
                        Container(
                          width: Get.width,
                          decoration: BoxDecoration(
                             color:  Colors.white // Optional: add border radius
                          ),//声波纹.
                          child: Column(
                            children: [
                              Row(
                                mainAxisAlignment: MainAxisAlignment.end,
                                children: [
                                  Container(
                                    child: InkWell(
                                      onTap: () {
                                        if (!hasRotated) {
                                          animationController!.forward();
                                          hasRotated = true;
                                        } else {
                                          animationController!.reset();
                                          hasRotated = false;
                                        }

                                      },
                                      child: Container(
                                        padding: EdgeInsets.only(left: 10.w,right: 10.w,),
                                        child: Image.asset('assets/images/icon_realtime_roate.png',width: 20.w,height: 20.h),
                                      ),
                                    ),
                                  ),
                                  SizedBox(width: 20.w,)
                                ],
                              ),
                              Row(
                                children: [
                                  Image.asset('assets/images/icon_video_wave_sideline.png',width: 13.w,height: 13.h,),
                                  Expanded(child: CommonWidgets.getMyDivider()),
                                  /*Image.asset('assets/images/icon_audio_wave_realtime.png',width: 176.w,height: 24.h),*/
                                  audioService.isPlaying.value ?
                                  AudioWaveform(
                                    amplitudes: amplitudes.value,
                                    height: 24.h,
                                    width: MediaQuery.of(context).size.width * 0.5,
                                    waveColor: audioService.isPlaying.value ? Colors.blue : Colors.grey,
                                  ): Image.asset('assets/images/icon_audio_wave_realtime.png',width: 176.w,height: 24.h),
                                  Expanded(child: CommonWidgets.getMyDivider()),
                                  Image.asset('assets/images/icon_video_wave_sideline.png',width: 13.w,height: 13.h,),

                                ],
                              )

                            ],
                          ),
                        ),
                        Container(
                          width: Get.width,
                          height: 278.h,
                          decoration: BoxDecoration(
                            color:  Colors.white,
                            borderRadius: BorderRadius.only(bottomLeft: Radius.circular(8),bottomRight: Radius.circular(8)), // Optional: add border radius
                          ),
                          child: Stack(
                            children: [
                              audioService.finalToLanguage.value == ''? Container(
                                child: Center(
                                  child: Column(
                                    children: [
                                      SizedBox(height: 80.h,),
                                      Image.asset('assets/images/empty_list_realtime.png',width: 169.w,height: 91.h),
                                      SizedBox(height: 16.h,),
                                      Text('点击下方开始键开始同声翻译',style: AppStyleThemeData.HINT_TEXT_STYLE_small,)

                                    ],
                                  ),
                                ),
                              ): Container(
                                padding: EdgeInsets.only(top: 45.h,left: 20.w,right: 20.w,bottom: 50.h),
                                child: SingleChildScrollView(
                                  controller: fromController,
                                  child: Text(audioService.finalFromLanguage.value,style: TextStyle(
                                      color: AppColors.big_title_color,
                                      fontSize: realTranslationController!.fontSize.value.sp
                                  )),
                                ),
                              ),
                              Positioned(
                                child: Text('${audioService.fromLanFlagDisplay.value}',style: AppStyleThemeData.HINT_TEXT_STYLE_small),
                                left: 15.w,
                                top: 15.h,
                              )

                            ],
                          ),
                        )
                      ],
                    ),
                  ),
                  Container(
                    color: Colors.white,
                    width: Get.width,
                    padding: EdgeInsets.only(bottom: 16.h,left: 10.w,right: 10.w,top: 14.h),
                    child: Row(
                      mainAxisAlignment:  MainAxisAlignment.spaceBetween,
                      children: [
                        InkWell(
                          onTap: () {
                            showLanguagePoupWindow(context);
                          },
                          child: Container(
                            padding: EdgeInsets.only(top:8.h,bottom:5.h),
                            child: Column(
                              children: [
                                Obx(()=>Text('${audioService.fromLanFlagDisplay.value.substring(0,1) + '-' +
                                    audioService.toLanFlagDisplay.value.substring(0,1)}',style: AppStyleThemeData.normal_bold_small,)),
                                Text('语言设置',style: AppStyleThemeData.normal_bold_small,)
                              ],
                            ),
                          ),
                        ),
                        InkWell(
                          onTap: () {
                            showFontPoupWindow(context);
                          },
                          child: Container(
                            padding: EdgeInsets.only(top:8.h,bottom: 8.h),
                            child: Column(
                              children: [
                                Text('${realTranslationController!.fontSizeShow.value}',style: AppStyleThemeData.normal_bold_small,),
                                Text('字体大小',style: AppStyleThemeData.normal_bold_small,)
                              ],
                            ),
                          ),
                        ),
                        Container(
                          child: InkWell(
                            onTap: () {
                              if (_isCoolingDown) {
                                return;
                              };

                              _isCoolingDown = true;

                              if (!audioService.isPlaying.value) {
                                _simulateAudioData();
                                audioService.record();
                              } else {
                                _stopSimulateAudioData();
                                audioService.pauseRecorder();
                              }

                              _debounceTimer = Timer(Duration(milliseconds: 500), () {
                                _isCoolingDown = false;
                              });


                            },
                            child: audioService.isPlaying.value ? Image.asset('assets/images/icon_play_realtime_btn_running.png',width: 55.w,height: 55.h):
                            Image.asset('assets/images/icon_play_realtime_btn.png',width: 55.w,height: 55.h),
                          ),
                        ),
                        InkWell(
                          onTap: () {
                            showOverlayWindow(context);
                          },
                          child: Container(
                            padding: EdgeInsets.only(top:8.h,bottom: 8.h),

                            child: Column(
                              children: [
                                Image.asset('assets/images/icon_double_languages.png',width: 24.w,height: 24.h),
                                Text('浮窗显示',style: AppStyleThemeData.normal_bold_small,)
                              ],
                            ),
                          ),
                        ),
                        InkWell(
                          onTap: () {
                             // showFontPoupWindow(context);
                            Tips.showToast('构建中...');
                          },
                          child: Container(
                            padding: EdgeInsets.only(top:8.h,bottom: 8.h),
                            child: Column(
                              children: [
                                Image.asset('assets/images/icon_audio_speaker_btn.png',width: 24.w,height: 24.h),
                                Text('语音播报',style: AppStyleThemeData.normal_bold_small,)
                              ],
                            ),
                          ),
                        )

                      ],
                    ),
                  )
                ],
              ))

            ],
          ),
        )
    ),
      top: false,);
  }

  @override
  void deactivate() {
    saveTranslationRecords();
    audioService.stopRecorder();
    _debounceTimer?.cancel(); // 组件销毁时取消计时器
    if (_audioWavetimer != null) {
      _audioWavetimer?.cancel();
    }

    super.deactivate();

  }

  void showPoupWindow(BuildContext context) {
    showModalBottomSheet(
        context: context,
        builder: (context) => StatefulBuilder(
          builder: (context, setState) {
            return Obx(()=>SafeArea(child: Container(
              padding: EdgeInsets.all(15.h),
              child: SingleChildScrollView(
                scrollDirection: Axis.horizontal,
                child: Row(
                  children: [
                    InkWell(
                      onTap: () {
                        if (_isCoolingDown) {
                          return;
                        };

                        _isCoolingDown = true;

                        if (!audioService.isPlaying.value) {
                          audioService.record();
                        } else {
                          audioService.pauseRecorder();
                        }

                        _debounceTimer = Timer(Duration(milliseconds: 800), () {
                          _isCoolingDown = false;
                        });

                      },
                      child: Obx(()=>Container(
                        child: audioService.isPlaying.value ? Image.asset('assets/images/icon_play_realtime_btn_running.png',width: 55.w,height: 55.h):
                        Image.asset('assets/images/icon_play_realtime_btn.png',width: 55.w,height: 55.h),
                      )),
                    ),
                    SizedBox(width: 20.w,),
                    InkWell(
                      onTap: () {
                        Get.back();
                        showFontPoupWindow(context);
                      },
                      child: Container(
                        padding: EdgeInsets.all(8.w),
                        decoration: BoxDecoration(
                          boxShadow: [
                            CommonWidgets.getBoxShadow(),
                          ],
                          color:  Colors.white,
                          borderRadius: BorderRadius.circular(8), // Optional: add border radius
                        ),
                        child: Column(
                          mainAxisSize: MainAxisSize.min,
                          children: [
                            Text('${realTranslationController!.fontSizeShow.value}',style: AppStyleThemeData.normal_bold_small,),
                            Text('字体大小',style: AppStyleThemeData.normal_bold_small,)
                          ],
                        ),
                      ),
                    ),
                    SizedBox(width: 20.w,),
                    Visibility(
                      visible: false, // 字幕共享功能未开发，暂时隐藏
                      child: Container(
                        padding: EdgeInsets.all(8.w),
                        decoration: BoxDecoration(
                          boxShadow: [
                            CommonWidgets.getBoxShadow(),
                          ],
                          color:  Colors.white,
                          borderRadius: BorderRadius.circular(8), // Optional: add border radius
                        ),
                        child: Column(
                          mainAxisSize: MainAxisSize.min,
                          children: [
                            Image.asset('assets/images/icon_screen_share_realtime.png',width: 16.w,height: 16.h),
                            Text('字幕共享',style: AppStyleThemeData.normal_bold_small,)
                          ],
                        ),
                      ),),

                    SizedBox(width: 20.w,),
                    InkWell(
                      onTap: () {
                        showLanguagePoupWindow(context);
                      },
                      child: Container(
                        padding: EdgeInsets.only(top:8.h,bottom:8.h,left: 17.w,right: 27.w),
                        decoration: BoxDecoration(
                          boxShadow: [
                            CommonWidgets.getBoxShadow(),
                          ],
                          color:  Colors.white,
                          borderRadius: BorderRadius.circular(8), // Optional: add border radius
                        ),
                        child: Column(
                          mainAxisSize: MainAxisSize.min,
                          children: [
                            Text(audioService.fromLanFlagDisplay.value.substring(0,1) + '-' +
                                audioService.toLanFlagDisplay.value.substring(0,1),style: AppStyleThemeData.normal_bold_small,),
                            Text('语言设置',style: AppStyleThemeData.normal_bold_small,)
                          ],
                        ),
                      ),
                    )
                  ],
                ),
              ),
            )));
          },
        ),
        backgroundColor: Colors.white.withValues(alpha: 0.5),
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.vertical(
            top: Radius.zero, // 顶部直角
          ),
        ),
        barrierColor: Colors.black.withValues(alpha: 0.1)
    );
  }


  void showFontPoupWindow(BuildContext context) {
    showModalBottomSheet(
        context: context,
        builder: (context) => SafeArea(child: Container(
          height: 280.h,
          padding: EdgeInsets.all(15.h),
          child: SingleChildScrollView(
            child: Column(
              children: [
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    Text('字体大小', style: AppStyleThemeData.HINT_TEXT_STYLE_small,),
                    InkWell(
                      onTap: () {
                        Get.back();
                      },
                      child: Image.asset('assets/images/icon_poup_window_close.png',width: 10.w,height: 10.h),
                    )

                  ],
                ),
                SizedBox(height: 15.h,),
                CommonWidgets.getMyDivider(),
                SizedBox(height: 15.h,),
                InkWell(
                  onTap: () {
                    realTranslationController!.fontSize.value = 32;
                    realTranslationController!.fontSizeShow.value = '32 (偏大)';
                    Get.back();
                  },
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      Text('32 (偏大)',style: realTranslationController!.fontSize.value == 32 ? TextStyle(
                          color: AppColors.app_base_theme_color,
                          fontSize: 14.sp
                      ): TextStyle(
                          color: Colors.black,
                          fontSize: 14.sp
                      ),),
                    ],
                  ),
                ),
                SizedBox(height: 15.h,),
                CommonWidgets.getMyDivider(),
                SizedBox(height: 15.h,),
                InkWell(
                  onTap: (){
                    realTranslationController!.fontSizeShow.value = '24 (大)';
                    realTranslationController!.fontSize.value = 24;
                    Get.back();
                  },
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      Text('24 (大)',style: realTranslationController!.fontSize.value == 24 ?TextStyle(
                          color: AppColors.app_base_theme_color,
                          fontSize: 14.sp
                      ): TextStyle(
                          color: Colors.black,
                          fontSize: 14.sp
                      )),
                    ],
                  ),
                ),
                SizedBox(height: 15.h,),
                CommonWidgets.getMyDivider(),
                SizedBox(height: 15.h,),
                InkWell(
                  onTap: () {
                    setState(() {
                      realTranslationController!.fontSizeShow.value = '18 (适中)';
                      realTranslationController!.fontSize.value = 18;
                    });
                    Get.back();
                  },
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      Text('18 (适中)',style: realTranslationController!.fontSize.value == 18 ? TextStyle(
                          color: AppColors.app_base_theme_color,
                          fontSize: 14.sp
                      ): TextStyle(
                          color: Colors.black,
                          fontSize: 14.sp
                      )),
                    ],
                  ),
                ),
                SizedBox(height: 15.h,),
                CommonWidgets.getMyDivider(),
                SizedBox(height: 15.h,),
                InkWell(
                  onTap: () {
                    setState(() {
                      realTranslationController!.fontSizeShow.value = '16 (小)';
                      realTranslationController!.fontSize.value = 16;
                    });
                    Get.back();
                  },
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      Text('16 (小)',style: realTranslationController!.fontSize.value == 16? TextStyle(
                          color: AppColors.app_base_theme_color,
                          fontSize: 14.sp
                      ): TextStyle(
                          color: Colors.black,
                          fontSize: 14.sp
                      )),
                    ],
                  ),
                ),
              ],
            ),
          ),
        )),
        backgroundColor: Colors.white
    );
  }


  void showLanguagePoupWindow(BuildContext context) {
    showModalBottomSheet(
        context: context,
        builder: (context) => StatefulBuilder(
          builder: (context, setState) {
            return Obx(()=>SafeArea(child: Container(
              padding: EdgeInsets.all(15.h),
              child: Column(
                mainAxisSize: MainAxisSize.min,
                children: [
                  Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      Text('语言设置', style: AppStyleThemeData.HINT_TEXT_STYLE_small,),
                      InkWell(
                        onTap: () {
                          Get.back();
                        },
                        child: Image.asset('assets/images/icon_poup_window_close.png',width: 10.w,height: 10.h),
                      )

                    ],
                  ),
                  SizedBox(height: 15.h,),
                  CommonWidgets.getMyDivider(),
                  SizedBox(height: 15.h,),
                  Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      InkWell(
                        onTap: () {
                          chooseFromLanguages(setState);
                        },
                        child: Container(
                          width: 135.w,
                          height: 48.h,
                          padding: EdgeInsets.all(8.w),
                          decoration: BoxDecoration(
                            boxShadow: [
                              CommonWidgets.getBoxShadow(),
                            ],
                            color:Colors.white,
                            borderRadius: BorderRadius.circular(8), // Optional: add border radius
                          ),
                          child: Center(
                            child: Text('${ audioService.fromLanFlagDisplay.value}',style: AppStyleThemeData.normal_bold,
                              maxLines: 1,
                              overflow: TextOverflow.ellipsis,
                            ),
                          ),
                        ),
                      ),

                      Container(
                        padding: EdgeInsets.all(14.w),
                        height: 48.h,
                        decoration: BoxDecoration(
                          boxShadow: [
                            CommonWidgets.getBoxShadow(),
                          ],
                          color:Colors.white,
                          borderRadius: BorderRadius.circular(8), // Optional: add border radius
                        ),
                        child: Image.asset('assets/images/icon_index_lang_exchange.png',width: 20.w,height: 20.h,),
                      ),
                      InkWell(
                        onTap: () {
                          chooseToLanguages(setState);
                        },
                        child: Container(
                          width: 135.w,
                          height: 48.h,
                          padding: EdgeInsets.all(8.w),
                          decoration: BoxDecoration(
                            boxShadow: [
                              CommonWidgets.getBoxShadow(),
                            ],
                            color:Colors.white,
                            borderRadius: BorderRadius.circular(8), // Optional: add border radius
                          ),
                          child: Center(
                            child: Text('${audioService!.toLanFlagDisplay.value}',style: AppStyleThemeData.normal_bold,
                              maxLines: 1,
                              overflow: TextOverflow.ellipsis,
                            ),
                          ),
                        ),
                      )
                    ],
                  ),
                  SizedBox(height: 15.h,),
                  Container(
                    width: Get.width,
                    child: ElevatedButton(onPressed: () {
                      changeLanguageReInitial();
                      Get.back();
                    }, child: Text('确定')),
                  ),
                ],
              ),
            )));
          },
        ),
        backgroundColor: Colors.white
    );
  }

  void changeLanguageReInitial() {
    if (audioService.isPlaying.value) {
      audioService.pauseRecorder();
    }

    audioService.reInitWs();
    audioService.connectedWsAndRecorder('wss://${NetWorkManager.WS_IP+NetWorkManager.SPEECH_RECOGNITION}?transStrategy=1&enableInterlingual=1',
        DataCallBack(
        confirmCallBack: (v) {
          audioService.record();
        }
    ));
  }


  void chooseFromLanguages(setState) async {
    final languageItem = await Get.toNamed(Routes.LANGUAGE_OPINION,parameters: {
      'code': audioService.fromLanguage
    });
    audioService.fromLanguage = languageItem['code'];
    audioService.fromLanFlagDisplay.value = languageItem['desc'];

  }

  void chooseToLanguages(setState) async {
    final languageItem = await Get.toNamed(Routes.LANGUAGE_OPINION,parameters: {
      'code': audioService.toLanguage
    });
    audioService.toLanguage = languageItem['code'];
    audioService.toLanFlagDisplay.value = languageItem['desc'];

  }


  void saveTranslationRecords() {
    if (audioService.finalFromLanguage.value.trim() != '' && audioService.finalToLanguage.value.trim() != '') {
      DbDAOHelper().saveTranslateHistory(audioService.fromLanguage, audioService.toLanguage,
          audioService.finalFromLanguage.value, audioService.finalToLanguage.value, realTranslationController!.taskId?? '01010101010101',AppConst.TRANSLATOIN_TYPE_REALTIME,
      audioService.fromLanFlagDisplay.value,audioService.toLanFlagDisplay.value);
    }

  }


  void showOverlayWindow(BuildContext context) async {
    if(!audioService.isPlaying.value) {
      Tips.showToast('请先开始录音.');
      return;
    }

    bool status = await FlutterOverlayWindow.isPermissionGranted();
    if (!status) {
      bool? result = await FlutterOverlayWindow.requestPermission();
      if (result!) {
        Tips.showToast('已经获取到权限');
      } else {
        Tips.showToast('未获取到授权.');
        return;
      }
    }

    FlutterOverlayWindow.isActive().then((show) async {
      if(show) {
        await FlutterOverlayWindow.closeOverlay();
      } else {
        await FlutterOverlayWindow.showOverlay(
          flag: OverlayFlag.defaultFlag,
          visibility: NotificationVisibility.visibilityPublic,
          width: (CommonUtil.getScreenSize_ofWidth(context)*0.95).toInt(),
          height: (MediaQuery.of(context).size.height * 0.7).toInt(),
          startPosition: const OverlayPosition(0, -259),
          overlayTitle: "SmartTranslator",
          overlayContent: '浮窗运行中',
          positionGravity: PositionGravity.left,
          enableDrag: true,
        );
        FlutterAppMinimizerPlus.minimizeApp();


      }
    });

  }


  void quite() {
    if (audioService.isPlaying.value) {
      CommonWidgets.showConfirmDialog(Get.context!, '提示', '返回后将关闭并退出同声翻译', '退出', '悬浮窗显示', DataCallBack(
          confirmCallBack: (v) {
            Get.back(); //退出听译.
          },
          cancleCallBack: (v) {
            FlutterOverlayWindow.isActive().then((show) async {
              if (show) {
                FlutterAppMinimizerPlus.minimizeApp();
              } else {
                showOverlayWindow(Get.context!);
              }
            });



          }
      ));
    } else {
      Get.back();
    }
  }


  void showAudioLogsPoupWindow(BuildContext context) {
    showModalBottomSheet(
        context: context,
        builder: (context) => SafeArea(child: Container(
          padding: EdgeInsets.all(15.h),
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              Obx(()=> Column(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Wrap(children: [
                    Text('Recording: ${audioService.showLogText.value}')
                  ]),
                ],
              ))
            ],
          ),
        )),
        backgroundColor: Colors.white
    );
  }



  void _simulateAudioData() {
    _audioWavetimer = Timer.periodic(const Duration(milliseconds: 150), (timer) {
    amplitudes.value = List.generate(50, (index) {
        // 生成0-15000之间的随机振幅（模拟16位PCM数据）
        return Random().nextDouble() * (15000 - 5000) + 5000;
    });


    });
  }

  void _stopSimulateAudioData() {
    amplitudes.value = [];

    _audioWavetimer?.cancel();
  }

}



